package org.pub.app.lunch;

import java.io.ByteArrayInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class PaxInputActivity extends Activity {

	private ArrayList<Segment> segList = new ArrayList<Segment>();
	private EditText editTextRsvName;
	private EditText editTextRsvId;
	private EditText editTextRsvEmail;
	private EditText editTextPaxLastName;
	private EditText editTextFirstName;
	private RadioGroup sexGroup;
	private RadioButton radioButton1;
	private RadioButton radioButton2;
	private TextView infoOw;
	private TextView infoRt;
	private Spinner spinnerOw;
	private Spinner spinnerRt;
	// private ArrayList<String[]> dcList = new ArrayList<String[]>();
	private ArrayList<String> CodeOw = new ArrayList<String>();
	private ArrayList<String> FareOw = new ArrayList<String>();
	private ArrayList<String> DcNameOw = new ArrayList<String>();
	private ArrayList<String> PaxTypeOw = new ArrayList<String>();

	private ArrayList<String> CodeRt = new ArrayList<String>();
	private ArrayList<String> FareRt = new ArrayList<String>();
	private ArrayList<String> DcNameRt = new ArrayList<String>();
	private ArrayList<String> PaxTypeRt = new ArrayList<String>();
	private String xml = "";
	private ArrayAdapter<String> arrayAdapterOw;
	private ArrayAdapter<String> arrayAdapterRt;
	private ProgressShowz progress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pax);

		progress = new ProgressShowz(this);
		progress.showDialogBar();

		Intent in = getIntent();

		QueryData query = in.getExtras().getParcelable("query");
		infoOw = (TextView) findViewById(R.id.owInfo);
		infoRt = (TextView) findViewById(R.id.rtInfo);
		spinnerOw = (Spinner) findViewById(R.id.owSpinner);
		spinnerRt = (Spinner) findViewById(R.id.rtSpinner);

		SegHolding segSync = new SegHolding(segHandler, in);
		segSync.start();
		// segSync.join();

		arrayAdapterOw = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DcNameOw);
		arrayAdapterOw.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerOw.setAdapter(arrayAdapterOw);

		if (Integer.parseInt(query.getTot_step()) > 1) {
			arrayAdapterRt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DcNameRt);
			arrayAdapterRt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerRt.setAdapter(arrayAdapterRt);
		}
		
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		//RelativeLayout layout = (RelativeLayout)inflater.inflate(resource, root)
		/*
		  &paxType1=A 
		  &ln1= //성 
		  &gn1= //이름 
		  &sex1=M 
		  &ic1=AD00 
		  &rc1=AD00 
		  &omc1= //마일리지
		  
		  &Flight_Fare1= 
		  &TopasSession1= 
		  &SEGIN1= 
		  
		  &adult= 
		  &child= 
		  &tot_step= 
		  &mobile= //핸드폰 
		  &ppn= //전화번호 
		  &email=
		  &cu_id= 
		  &resUserName= 
		  &ing=Y 
		  &android=
		 */

	}

	private String readXml(String availUrl, List<NameValuePair> params) throws Exception {
		try {

			HttpClient client = new DefaultHttpClient();

			HttpPost post = new HttpPost(availUrl);
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);
			HttpEntity resEntity = responsePOST.getEntity();

			System.out.println(ent);
			System.out.println(params);
			return EntityUtils.toString(resEntity);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private Handler segHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				Document xmlDoc;
				xml = (String) msg.obj;
				try {
					xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("euc-kr")));

					NodeList ResponseAirDomSaleList = xmlDoc.getElementsByTagName("ResponseAirDomSale");

					for (int i = 0; i < ResponseAirDomSaleList.getLength(); i++) {

						NodeList SaleCodeListList = ((Element) ResponseAirDomSaleList.item(i)).getElementsByTagName("SaleCodeList");

						for (int j = 0; j < SaleCodeListList.getLength(); j++) {
							Element SaleCodeList = (Element) SaleCodeListList.item(j);
							String CodeTmp = "";
							if (SaleCodeList.getElementsByTagName("Code").item(0).getFirstChild() != null) {
								CodeTmp = SaleCodeList.getElementsByTagName("Code").item(0).getFirstChild().getNodeValue();
							}

							String FareTmp = SaleCodeList.getElementsByTagName("Fare").item(0).getFirstChild().getNodeValue();
							DecimalFormat df = new DecimalFormat("#,###");
							FareTmp = df.format(Double.parseDouble(FareTmp));
							String DcNameTmp = SaleCodeList.getElementsByTagName("DcName").item(0).getFirstChild().getNodeValue();
							String PaxTypeTmp = SaleCodeList.getElementsByTagName("PaxType").item(0).getFirstChild().getNodeValue();
							// dcList.add(new String[] { Code, Fare, DcName,
							// PaxType });
							if (i == 0) {
								CodeOw.add(CodeTmp);
								FareOw.add(FareTmp);
								DcNameOw.add(FareTmp + " " + DcNameTmp);
								PaxTypeOw.add(PaxTypeTmp);
							} else {
								CodeRt.add(CodeTmp);
								FareRt.add(FareTmp);
								DcNameRt.add(FareTmp + " " + DcNameTmp);
								PaxTypeRt.add(PaxTypeTmp);
							}

							if (i == 0) {
								arrayAdapterOw.notifyDataSetChanged();
								System.out.println("notifyDataSetChanged OW");
							} else {
								arrayAdapterRt.notifyDataSetChanged();
								System.out.println("notifyDataSetChanged RT");

							}
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
				}

				progress.mHandler.sendMessage(progress.mHandler.obtainMessage(100));

				break;
			}

		}

	};

	public class SegHolding extends Thread {
		Intent in;
		Handler handler;

		public SegHolding(Handler handler, Intent in) {
			this.handler = handler;
			this.in = in;

		}

		@Override
		public void run() {

			try {

				int tot_step = in.getExtras().getInt("tot_step");
				segList = in.getExtras().getParcelableArrayList("segList");

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("tot_step", String.valueOf(tot_step)));
				params.add(new BasicNameValuePair("android", ""));

				for (int i = 0; i < segList.size(); i++) {

					Segment segment = segList.get(i);

					params.add(new BasicNameValuePair("DEP_CITY" + (i + 1), segment.getDepCity()));
					params.add(new BasicNameValuePair("DEP_DATE" + (i + 1), segment.getDepDateTime().substring(0, 8)));
					params.add(new BasicNameValuePair("DEP_TIME" + (i + 1), segment.getDepDateTime().substring(8)));
					params.add(new BasicNameValuePair("ARR_CITY" + (i + 1), segment.getArrCity()));
					params.add(new BasicNameValuePair("ARR_DATE" + (i + 1), segment.getArrDateTime().substring(0, 8)));
					params.add(new BasicNameValuePair("ARR_TIME" + (i + 1), segment.getArrDateTime().substring(8)));
					params.add(new BasicNameValuePair("CAR" + (i + 1), segment.getCarCode()));
					params.add(new BasicNameValuePair("CAR_NO" + (i + 1), segment.getMainFlt()));
					params.add(new BasicNameValuePair("CLASS_NAME" + (i + 1), segment.getClassCode()));
					params.add(new BasicNameValuePair("CURRENCY" + (i + 1), segment.getCurrency()));
					params.add(new BasicNameValuePair("FLIGHT_FARE" + (i + 1), segment.getFare()));
					params.add(new BasicNameValuePair("SEGIN" + (i + 1), segment.getItinInfo()));
					params.add(new BasicNameValuePair("Session" + (i + 1), segment.getSession()));

				}
				System.out.println("start");
				String url = getResources().getString(R.string.url_local);
				if (getResources().getString(R.string.url_info).equals("real")) {
					url = getResources().getString(R.string.url_real);
				} else if (getResources().getString(R.string.url_info).equals("test")) {
					url = getResources().getString(R.string.url_test);
				}
				url += "/booking/AwpDomAirIdFare.lts";

				xml = readXml(url, params);

				handler.sendMessage(handler.obtainMessage(1, xml));

				System.out.println("end");

			} catch (Exception e) {
				e.printStackTrace();
			}

			super.run();
		}

	}
}
